from django.utils import simplejson as json
from django.http import HttpResponse


class JSONBaseResponseMixin(object):
    """
    Renders a JSON response
    """

    def get_json_response(self, content, **kwargs):
        return HttpResponse(
            content,
            content_type="application/json",
            **kwargs
        )

    def convert_to_json(self, context):
        raise NotImplementedError

    def render_to_response(self, context, **response_kwargs):
        return self.get_json_response(self.convert_to_json(context))


class JSONPostsListsResponseMixin(JSONBaseResponseMixin):
    def convert_to_json(self, context):
        data = []
        posts_list = context['posts_list']
        is_logged_in = context.get('is_logged_in', None)
        url = context.get('absolute_url')

        for post in posts_list:
            if post.is_published or is_logged_in:
                datum = {
                    "uri": "%s%d" % (url, post.id),
                    "title": post.title,
                    "is_published": post.is_published,
                    "tags": [t.name for t in post.tags.all()],
                    }
                data.append(datum)

        return json.dumps(data)


class JSONPostDetailResponseMixin(JSONBaseResponseMixin):
    def convert_to_json(self, context):
        datum = None
        post = context['post']
        is_logged_in = context.get('is_logged_in', None)

        if post.is_published or is_logged_in:
            datum = {
                "title": post.title,
                "body": post.body,
                "is_published": post.is_published,
                "tags": [t.name for t in post.tags.all()],
                }

        return json.dumps(datum)
